<template>
  <div class="content">
    <div class="breadcrumb" :gutter="24">
      {{$t('model.model_mang')}}

    </div>
    <el-form ref="form" :model="formData" label-width="70px" size="small">
      <el-row :gutter="28">
        <el-col :xs="3" :sm="1" :md="1" :lg="1" :xl="1">
          <el-button type="primary" size="small" :icon="'iconfont ' + icon" class="change" @click="changePattern"></el-button>
        </el-col>
        <el-col :xs="9" :sm="6" :md="5" :lg="3" :xl="3">
          <el-form-item :label="$t('common.keyword')">
            <el-input v-model="formData.keyword" clearable placeholder=""></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="8" :md="10" :lg="7" :xl="5" class="titmepicker">
          <el-form-item :label="$t('common.create_time')">
            <el-date-picker v-model="formData.time" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
              :unlink-panels="true">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :xs="2" :sm="2" :md="2" :lg="2" :xl="2">
          <el-form-item label-width="0px">
            <el-button type="primary" size="small" @click="handleSearch">{{ $t("common.query") }}</el-button>
          </el-form-item>
        </el-col>

        <div class="btngroup">
          <el-button type="primary" size="small" @click="handleAdd()">{{ $t("common.add") }}</el-button>
          <el-button type="primary" size="small" @click="modifyRow()">{{ $t("common.edit") }}</el-button>
          <el-button type="primary" size="small" @click="handleDelete()">{{ $t("common.remove") }}</el-button>

          <el-button type="primary" size="small" @click="modifyStatus(2)">{{ $t("common.enable") }}</el-button>
          <el-button type="primary" size="small" @click="modifyStatus(3)">{{ $t("common.disable") }}</el-button>
        </div>
      </el-row>
    </el-form>
    <div class="dataContent">
      <tableList :tableData="tableData" :pager="pager" v-if="!isCard" :tableLoading="tableLoading" @handleEdit="handleEdit"
        @sortChange="sortChange"></tableList>
      <cardList @handleEdit="handleEdit" v-if="isCard" :tableData="tableData" :tableLoading="tableLoading"></cardList>
      <div class="pagination-area">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[20, 30, 50, 100]"
          :page-size="pager.pageSize" :current-page="pager.pageNum" layout="total, sizes, prev, pager, next, jumper" :total="pager.total">
        </el-pagination>
      </div>
    </div>

    <el-dialog v-dialogDrag :title="title" :visible.sync="isShowDialog" :close-on-click-modal="false" width="60vh" class="isShowDialog"
      :before-close="handleClose">
      <el-form :model="ruleForm" label-width="80px" ref="ruleForm" size="small" :rules="rules" :hide-required-asterisk="true">
        <el-row :gutter="35">
          <el-col :xs="24">
            <el-form-item :label="$t('model.model_name')" prop="woId">
              <el-input v-model="ruleForm.modelName" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('recipe.formula_name')" prop="recipeId">
              <el-select v-model="ruleForm.recipeId" remote filterable :remote-method="remoteMethod" placeholder=""
                v-el-select-loadmore="loadMoreFun" clearable @change="changeRecipeId">
                <el-option v-for="(item,index) in formulaList" :key="index" :label="item.recipeName" :value="item.fid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24">
            <el-form-item :label="$t('recipe.material_code')" prop="item">
              <el-input disabled v-model="ruleForm.item" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('dialog.numbers')" prop="itemQty">
              <el-input disabled v-model="ruleForm.itemQty" placeholder="" min="0" v-enterNumber2 type="number" clearable>
                <template slot="append">{{ruleForm.uomId}}</template>
              </el-input>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="handleAddFormula('ruleForm')"
          :loading="loading">{{ $t("common.preservation") }}</el-button>
        <el-button @click="handleClose()" size="small">{{ $t("common.cancel") }}</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { modeling } from "@/api/model"
import { scheduling } from "@/api/scheduling"
import tableList from "./template/tableList.vue"
import cardList from "./template/cardList.vue"
import { userAdmin } from "@/api/userAdmin"

export default {
  components: {
    tableList,
    cardList
  },
  data () {
    let woIdFn = (rule, value, callback) => {
      if (this.title == "新增" && value) {
        scheduling.workOrderCheck({ woId: value }).then(res => {
          console.log(res)
          if (res.code == 200) {
            callback();
          } else {
            callback(new Error('模型名称不能重复'));
          }
        }).catch(e => {
          callback(new Error('模型名称不能重复'));
        })
      } else if (!value) {
        callback(new Error('模型名称不能为空'));
      } else {
        callback();
      }
    }
    let lotNumFn = (rule, value, callback) => {
      if (this.title == "新增" && value) {
        scheduling.checkLot({ lotNum: value }).then(res => {
          if (res.code == 200) {
            callback();
          } else {
            callback(new Error('批次号已存在'));
          }
        })
      } else if (this.title == "编辑" && value) {
        scheduling.checkLot({ lotNum: value, woId: this.ruleForm.woId }).then(res => {
          if (res.code == 200) {
            callback();
          } else {
            callback(new Error('批次号已存在'));
          }
        })
      }
    }
    return {
      formData: {
        keyword: "",
        time: [],
        status: ['0', '1', '2', '4']
      },
      ruleForm: {
        recipeId: "",
        modelName: "",
        itemQty: "",
        uomId: "",
        creator: '',
      },
      pager: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
        field: 'createTime',
        order: 'DESC',
      },
      formulaPage: {
        pageNum: 1,
        pageSize: 2000,
      },
      keyword: "",
      formulaList: [],
      tableData: [],
      icon: "icon-biaoge",
      isShowDialog: false,
      loading: false,
      selectLoading: false,
      tableLoading: false,
      title: "新增",
      rules: {
        recipeId: [{ required: true, message: '配方名称不能为空', trigger: 'change' }],
        modelName: [
          { required: true, message: '模型名称不能为空', trigger: 'blur' },
        ],
      },
      secle: "",
      isCard: false,
      disabled: -1,

      currObj: {},
      sysUserVosList: [],
    }
  },
  created () {
    this.getSysUserList()
    this.getTbrecipeList()
    this.workOrderList()
  },
  methods: {
    modifyStatus (val) {
      const param = {
        fid: this.currObj.fid,
        statusCd: val,
      }
      modeling.modifyModelStatus(param).then(res => {
        if (res.code == 200) {
          this.$message({ duration: 1000, type: 'success', message: '修改成功!' });
          this.workOrderList()
        } else {
          this.$message({ duration: 1000, type: 'warn', message: '修改失败!' });
        }
      })
    },
    //获取配方名称列表
    getTbrecipeList () {
      const param = {
        recipeName: this.keyword,
        isRecipeStatus: [3, 6],
        page: this.formulaPage.pageNum,
        size: this.formulaPage.pageSize,
        field: 'recipeName,version',
        order: 'DESC',
      }
      this.selectLoading = true
      scheduling.getTbrecipeList(param).then(res => {
        this.selectLoading = false
        if (res.code == 200) {
          // this.formulaList = [...this.formulaList, ...res.data.rows]
          let obj = {};
          this.formulaList = res.data.rows.reduce((cur, next) => {
            obj[next.recipeName] ? "" : obj[next.recipeName] = true && cur.push(next);
            return cur;
          }, [])
          this.formulaList = this.$util.RemoveArr(this.formulaList, 'fid')
        }
      })
    },
    workOrderList () {
      let startTime = ""
      let endTime = ""
      if (this.formData.time && this.formData.time.length > 0) {
        startTime = this.$util.format(this.formData.time[0], 'YYYY-MM-DD')
      }
      if (this.formData.time && this.formData.time.length > 0) {
        endTime = this.$util.format(this.formData.time[1], 'YYYY-MM-DD')
      }
      const param = {
        page: this.pager.pageNum,
        size: this.pager.pageSize,
        modelName: this.formData.keyword,
        // stateCd: '',
        startTime: startTime,
        endTime: endTime,
        field: this.pager.field,
        order: this.pager.order,
        stateCds: this.formData.status
      }
      this.tableLoading = true
      let that = this
      modeling.modelProjectList(param).then(res => {
        this.tableLoading = false
        if (res.code == 200) {
          let rets = []
          res.data.rows.forEach(ii => {
            let kk = that.sysUserVosList.filter(jj => jj.fid == ii.creator)
            ii.creator = kk[0].frealName
            rets.push(ii)
          })
          this.tableData = rets //res.data.rows
          this.pager.total = res.data.total
        }
      }).catch(e => {
        this.tableLoading = false
      })
    },
    sortChange (column) {
      if (column.order === 'descending') {
        this.pager.field = column.prop
        this.pager.order = 'DESC'
      } else {
        this.pager.field = column.prop
        this.pager.order = 'ASC'
      }
      this.pager.pageNum = 1
      this.workOrderList()
    },
    handleSearch () {
      this.pager.pageNum = 1
      this.workOrderList()
    },
    loadMoreFun () {
      this.formulaPage.pageNum++
      this.getTbrecipeList()
    },
    //远程搜索配方名称
    remoteMethod (keyword) {
      this.keyword = keyword.trim();
      this.formulaPage.pageNum = 1
      setTimeout(() => {
        this.formulaList = []
        this.getTbrecipeList()
      }, 200)
    },
    handleAdd () {
      this.title = "新增"
      this.ruleForm = {}
      try {
        this.$refs['ruleForm'].resetFields();
      } catch (e) { }

      this.isShowDialog = true
    },
    changePattern () {
      this.isCard = !this.isCard
      this.secle = ''
      this.icon = this.isCard ? 'icon-qiehuan' : 'icon-biaoge'
    },
    handleEdit (row) {
      this.secle = row.radioId
      this.disabled = row.row.stateCd
      this.currObj = row.row
      console.log(row.row)
    },
    modifyRow () {
      if (this.secle === '') {
        this.$message.error('请选择要修改的信息');
        return
      }
      let row = this.tableData.find(item => item.fid == this.secle)
      const sysUser = this.sysUserVosList.find(el => el.frealName == row.creator)

      this.ruleForm = Object.assign({}, {
        recipeId: row.tbRecipe.fid,
        fid: row.fid,
        modelName: row.modelName,
        itemQty: row.tbRecipe.itemQty,
        item: row.tbRecipe.item,
        uomId: row.tbRecipe.uomId,
        createTime: row.createTime,
        creator: sysUser.fid,
      })
      this.title = "编辑"
      this.isShowDialog = true
    },
    handleSizeChange (val) {
      this.pager.pageNum = 1
      this.pager.pageSize = val
      this.workOrderList()
    },
    handleCurrentChange (val) {
      this.pager.pageNum = val;
      this.workOrderList()
    },
    //获取用户列表
    getSysUserList () {
      const param = {
        page: 1,
        size: 99999
      }
      userAdmin.getSysUserList(param).then(res => {
        if (res.code == 200) {
          if (res.data.rows && res.data.rows.length) {
            this.sysUserVosList = res.data.rows

          }

        }
      })
    },
    handleAddFormula (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let param = Object.assign({}, this.ruleForm)
          param.tbRecipeVo = {
            fid: ""
          }

          param.tbRecipeVo.fid = this.ruleForm.recipeId
          param.creator = this.ruleForm.creator
          this.loading = true
          modeling.addModelProject(param, this.title).then(res => {
            this.loading = false
            this.isShowDialog = false
            if (res.code == 200) {
              this.isShowDialog = false
              const el = this.tableData.find(item => item.woId == this.secle)
              if (el) {
                this.disabled = el.stateCd
              } else {
                this.disabled = -1
              }
              this.workOrderList()
              this.$message({ duration: 1000, type: 'success', message: '保存成功!' });
            } else {
              this.$message.error(res.msg);
            }
          }).catch(e => {
            this.isShowDialog = false
            this.loading = false
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },

    //删除工单
    handleDelete () {
      if (this.secle === '') {
        this.$message.error('请选择要删除的数据');
        return
      }
      let row = this.tableData.find(item => item.fid == this.secle)
      let that = this
      this.$customConfirm({
        content: "请确认是否删除" + this.currObj.modelName,
        onok () {
          modeling.removeModelProject(that.currObj.fid).then(res => {
            if (res.code == 200) {
              that.workOrderList()
              that.ruleForm = {}
              that.secle = ''
              that.disabled = -1
              that.$message({ duration: 1000, type: 'success', message: '删除成功!' });
            }
          })
        }
      });
    },


    handleClose () {
      this.isShowDialog = false
    },
    changeRecipeId (val) {
      let item = this.formulaList.find(item => item.fid == val)
      this.ruleForm.itemQty = item.itemQty
      this.ruleForm.item = item.item
      this.ruleForm.uomId = item.uomId
      this.ruleForm.type = item.recipeStatus == 3 ? '1' : item.recipeStatus == 6 ? '2' : ''
    },

  }
}
</script>

<style scoped>
.btngroup {
  float: right;
  margin-right: 20px;
}
.change >>> .iconfont {
  font-size: 13px !important;
}
.pagination-area {
  text-align: right;
  padding-top: 20px;
  padding-bottom: 10px;
}
.isShowDialog >>> .el-select,
.isShowDialog >>> .el-date-editor {
  width: 100%;
}
.isShowDialog >>> .el-date-editor .el-range-separator {
  width: 8%;
}
.titmepicker >>> .el-date-editor {
  width: 100%;
}
.titmepicker >>> .el-date-editor .el-range-separator {
  width: 8%;
}
@media only screen and (max-width: 768px) {
  .titmepicker {
    display: none;
  }
}
.dataContent {
  /* height: calc(100vh - 180px); */
  border: 1px solid #ebeef5;
  overflow: auto;
}
.marginLing >>> .el-row {
  margin-left: 0px !important;
  margin-right: 0px !important;
}
</style>